package com.dx.mes.service.spc.service;

import com.dx.common.table.ppt.Bis_m_item;
import com.dx.common.table.ppt.Spc_ret_mfg_data_diff;
import com.dx.mes.common.dao.IBisMItemDao;
import com.dx.mes.common.dao.ISpcRetMfgDataDiffDao;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.service.spc.tx.Xpcmsdt.XpcmsrdtI;
import com.dx.mes.service.spc.tx.Xpcmsdt.XpcmsrdtIA;
import com.dx.mes.service.spc.tx.Xpcmsdt.XpcmsrdtO;
import com.dx.mes.service.spc.util.FileListener;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_OK;

/**
 * Created by XXD on 2018/6/4.
 */
@Service
@PropertySource("classpath:filePaths.properties")
public class ParseFileService {
    private LogUtils logUtils;

    @Autowired
    ISpcRetMfgDataDiffDao spcRetMfgDataDiffDao;
    @Autowired
    private IFqprepdataService fqprepdataService;
    @Autowired
    private IBisMItemDao bisMItemDao;


    public List<Bis_m_item> queryItems(String tool_id_fk, String mes_id_fk) {
        String hql2 = "From Bis_m_item where tool_id_fk = '" + tool_id_fk+"'";
        hql2 += " and mes_id_fk = '" + mes_id_fk +"'";
        hql2 += " order by data_seq";
        List<Bis_m_item> bis_m_items = bisMItemDao.find(hql2);
        return bis_m_items;
    }

    //1号扩散机
    public void monitor1(){
        // 监控目录
        String rootDir = "C:/Users/m1310/Desktop/方阻txt文件";
        // 轮询间隔 5 秒
        long interval = TimeUnit.SECONDS.toMillis(5);
        // 创建一个文件观察器用于处理文件的格式
        FileAlterationObserver _observer = new FileAlterationObserver(
                rootDir,
                FileFilterUtils.and(
                        FileFilterUtils.fileFileFilter(),
                        FileFilterUtils.suffixFileFilter(".txt")),  //过滤文件格式
                null);
        FileAlterationObserver observer = new FileAlterationObserver(rootDir);

//        observer.addListener(new FileListener()); //设置文件变化监听器
        _observer.addListener(new FileListener());
        //创建文件变化监听器
        FileAlterationMonitor monitor = new FileAlterationMonitor(interval, _observer);
        try{
            // 开始监控
            monitor.start();
            System.out.println("***************监控中***************");
        }catch (Exception e){
            logUtils.error("异常处理 ："+e.toString());
        }
    }

    //扩散1号机方阻
    public void findCT01() throws Exception{
        String txtPath = "/home/test2/kuosan11";
        String lineId = "B";
        String txtNamePre = getTxtName();
        String txtpath = txtPath + "/" + txtNamePre+"-"+lineId+".txt";
//        String testpath = "/home/test2/kuosan11/18-06-13-N-B.txt";
        analysisTxt(txtpath);
    }


    //根据班别读取指定文件
    public String getTxtName() throws Exception{
        String txtNamePre= "";
        Date nowDate = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(nowDate);
        String txtdate = date.substring(2);//18-05-27
        //日班 都是当天
        if(Util.between8To20(nowDate)){
            txtNamePre = txtdate +"-D";
        }
        //夜班
        if(Util.between20To8(nowDate)){
            SimpleDateFormat formatdate  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String stringdate20N  = date +" 20:00:00";
            Date date20N = formatdate.parse(stringdate20N);
            String stringdate24N  = date + " 24:00:00";
            Date date24N = formatdate.parse(stringdate24N);
            //当天20;00 -24:00读当天日期的文件，过24：00-次日8：00,读前一天时间的文件
            if(Util.belongCalendar(nowDate,date20N,date24N)){
                txtNamePre = txtdate +"-N";
            }else{
                Calendar calendar = Calendar.getInstance(); //得到日历
                calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
                Date dBefore = calendar.getTime();   //得到前一天的时间
                String dateBefore = format.format(dBefore);
                String dateBefore2 = dateBefore.substring(2);//18-05-27
                txtNamePre = dateBefore2+"-N";
            }
        }
        return txtNamePre;
    }


    //解析文件
    public void analysisTxt(String path) throws Exception {
        logUtils = new LogUtils(TimingParseService.class);
        //根据系统当前时间读取指定文件 18-05-27-N
        String filePath = path;
        List<String> list = new ArrayList<String>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(filePath));
            String line = null;
            while ((line = br.readLine()) != null) {
                list.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放IO资源
            try {
                if (br != null) {
                    br.close();
                }
            } catch (Exception e) {
                logUtils.error(e.toString());
            }
        }

        System.out.println(list);

        List<String[]> newTxtList = new ArrayList<>();
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i).split("\\s+").length > 2) {
                //\s表示匹配任何空白字符，+表示匹配一次或多次
                newTxtList.add(list.get(i).split("\\s+"));
            }
        }

        System.out.println(newTxtList);
        //时间，方阻单点值
        Map<Timestamp, String> valueMap = new LinkedHashMap<Timestamp, String>();
        for (int i = 0; i < newTxtList.size(); i++) {
            String date = newTxtList.get(i)[0];
            String time = newTxtList.get(i)[1].substring(0, 8);
            String dataTime = date.replace(".", "-") + " " + time;
            Timestamp dataTimestamp = Timestamp.valueOf(dataTime);
            valueMap.put(dataTimestamp, newTxtList.get(i)[3]);
        }
        System.out.println(valueMap);

        //配置的ITEM项
        List<Bis_m_item> bisMItemList = queryItems("CT11", "KSAUTOFZ");

        //先查edc表中最新的一笔数据的时间
        String hql = "From Spc_ret_mfg_data_diff where tool_id_fk ='" + "CT11" + "'";
        hql += " and mes_id_fk = '" + "KSAUTOFZ" + "'";
        hql += " order by rpt_timestamp desc";
        List<Spc_ret_mfg_data_diff> spcRetMfgDataDiffList = spcRetMfgDataDiffDao.find(hql);
        Timestamp rptTimestamp = null;
        if (spcRetMfgDataDiffList != null && spcRetMfgDataDiffList.size() > 0) {
            rptTimestamp = spcRetMfgDataDiffList.get(0).getRpt_timestamp();
            for (Map.Entry<Timestamp, String> entry : valueMap.entrySet()) {
                Timestamp timestamp = entry.getKey();
                //txt文件数据时间小于已存在的rptTimestamp
                if (timestamp.compareTo(rptTimestamp) <= 0) {
                    continue;
                } else {
                    XpcmsrdtO xpcmsrdtO = new XpcmsrdtO();
                    List<String> valueList = new ArrayList<>();
                    valueList.add(entry.getValue());
                    XpcmsrdtI xpcmsrdtI = sendTrx(bisMItemList, valueList, "CT11", "KSAUTOFZ", timestamp);
                    xpcmsrdtO = autoReportSPC(xpcmsrdtI);
                    if (!xpcmsrdtO.getRtn_code().equals(RETURN_CODE_OK)) {
                        logUtils.error(xpcmsrdtO.getRtn_mesg());
                        continue;
                    }
                    logUtils.info(entry.getKey() + ":" + entry.getValue());
                    System.out.println(entry.getKey() + ":" + entry.getValue());
                }
            }
        } else {
            //TODO 没有数据则全部增加
            saveAllTxtValue(valueMap,bisMItemList);
        }

    }

    public void  saveAllTxtValue(Map<Timestamp, String> valueMap,List<Bis_m_item> bisMItemList){
        for (Map.Entry<Timestamp, String> entry : valueMap.entrySet()) {
            Timestamp timestamp = entry.getKey();
            XpcmsrdtO xpcmsrdtO = new XpcmsrdtO();
            List<String> valueList = new ArrayList<>();
            valueList.add(entry.getValue());
            XpcmsrdtI xpcmsrdtI = sendTrx(bisMItemList, valueList, "CT11", "KSAUTOFZ", timestamp);
            xpcmsrdtO = autoReportSPC(xpcmsrdtI);
            if (!xpcmsrdtO.getRtn_code().equals(RETURN_CODE_OK)) {
                logUtils.error(xpcmsrdtO.getRtn_mesg());
                continue;
            }
            System.out.println(entry.getKey() + ":" + entry.getValue());
            logUtils.info(entry.getKey() + ":" + entry.getValue());
        }
    }


    //普通文件组intrx
    private XpcmsrdtI sendTrx(List<Bis_m_item> bis_m_items, List<String> valueList, String toolId, String mesIdFk, Timestamp proc_timestamp) {
        XpcmsrdtI trxI = new XpcmsrdtI();
        Integer vlsize = valueList.size();//上报的数据
        Integer itemsize = bis_m_items.size();//设置的item
        List<XpcmsrdtIA> iaryList = new ArrayList<XpcmsrdtIA>();
        for (int m = 0; m < vlsize; m++) {
            if (m >= itemsize) {
                break;
            }
            String value = valueList.get(m);//如何确定这个value对应了datagroup对应了datagroupseq
            if (!StringUtils.isEmpty(value)) {
                XpcmsrdtIA iary = new XpcmsrdtIA();
                iary.setData_group(bis_m_items.get(m).getData_group());
                iary.setData_value(value);
                iary.setData_group_seq(bis_m_items.get(m).getData_group_seq());
                iary.setData_type("03");
                iaryList.add(iary);
            }
        }
//        trxI.setPrd_seq_id(glassId);
        trxI.setTool_id(toolId);
        trxI.setMes_id_fk(mesIdFk);
//        trxI.setMdl_id_fk(mdlIdFk);
        trxI.setRep_unit_fk("M");
        trxI.setData_pat_fk("00");
        trxI.setFlag("A");
        trxI.setOpe_id("扩散");
        trxI.setData_cnt(String.valueOf(iaryList.size()));
        trxI.setIary(iaryList);
        trxI.setEvt_timestamp(proc_timestamp);
        return trxI;
    }

    private XpcmsrdtO autoReportSPC(XpcmsrdtI inTrx){
        XpcmsrdtI xpcmsrdtI = inTrx;
        XpcmsrdtO xpcmsrdtO = new XpcmsrdtO();
        xpcmsrdtO.setTrx_id("FQPEDCDAT");
        xpcmsrdtO.setTrx_id("O");

        String strOutTrx = fqprepdataService.subMainProc(AppContext.getCurrEventNumber(),
                JacksonUtil.toJSONStr(xpcmsrdtI));
        xpcmsrdtO = JacksonUtil.fromJson(strOutTrx, XpcmsrdtO.class);
        return xpcmsrdtO;
    }


}
